package com.choosefine.it.basedata.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.choosefine.it.base.dto.PageDTO;
import com.choosefine.it.basedata.dao.UserMapper;
import com.choosefine.it.basedata.model.User;
import com.choosefine.it.basedata.model.dto.FindUserDTO;
import com.choosefine.it.basedata.model.dto.UserSearchDTO;
import com.choosefine.it.basedata.model.vo.UserSearchVO;
import com.choosefine.it.basedata.model.vo.UserVO;
import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.exception.RespExcption;
import com.choosefine.it.common.model.CustomRestTemplate;
import com.choosefine.it.common.utils.Assert;
import com.choosefine.it.common.utils.DateUtils;
import com.choosefine.it.common.utils.PagedResult;
import com.choosefine.it.common.utils.StringUtils;
import com.choosefine.it.common.utils.URLHandlerUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 
 * @desc 用户相关操作Service
 * @author 戚羿辰
 * @Date   2017/01/20
 */
@Service("userService")
public class UserService {
	@Autowired
	UserMapper			userMapper;

	@Autowired
	CustomRestTemplate	restTemplate;

	/**用户模块**/
	@Value("#{yaml.get('service.usercent.url')}")
	String				USER_MODEL			= null;
	/** 删除用户 **/
	@Value("#{yaml.get('user.deleteUserByPhone')}")
	String				DEL_USER_BY_PHONE	= null;

	@SuppressWarnings("rawtypes")
	public int deleteByPrimaryKey(Integer id) {
		// 删除主登陆账号需要关联所有相同号码的登录账号
		User user = findByPrimaryKey(id);
		if (null == user) {
			return 0;
		}
		Map<String, Object> map = new HashMap<>();
		ResponseEntity<Map> result = null;
		int num = 0;
		if (user.getType() == CommonConstant.USER_TYPE_MAIN)
		{
			num = userMapper.deleteByPhone(user.getPhone(), CommonConstant.USER_TYPE_MAIN);
			map.put("phone", user.getPhone());
		} else
		{
			num = userMapper.deleteByPrimaryKey(id);
			map.put("phone", user.getUserName());
		}
		
		StringBuffer url= URLHandlerUtils.getUrlBuffer(USER_MODEL, DEL_USER_BY_PHONE);
		String urlYX = URLHandlerUtils.DefaultUriTemplateHandler(url.toString(), map);
		result = restTemplate.exchange(urlYX, HttpMethod.DELETE, new HttpEntity<String>() {
		}, Map.class);
		boolean resultBool = null != result && result.getBody().get("status").toString().equals("200");
		Assert.assertEqu(resultBool, CommonConstant.MSG_PUSH_ERR);
		return num;
	}

	/**
	 * 根据userCode查找用户
	 * @param userCode 用户编号
	 */
	public UserSearchVO findByUserCode(String userCode) {
		UserSearchVO user = null;
		// 预校验
		Assert.assertStrNotNull(userCode, ResultCode.MSG_PARAMS_NULL);
		user = userMapper.findByUserCode(userCode, CommonConstant.USER_TYPE_MAIN);
		return user;
	}

	/**
	 * 根据userCode删除用户(禁用)
	 * @param map	删除条件
	 * @return int	删除条数
	 */
	public int deleteByUserCode(Map<String, Object> map) {
		int num = 0;
		num = userMapper.deleteByUserCode(map);
		// 后校验
		Assert.assertTrue(num > 0, ResultCode.MSG_ERROR);
		return num;
	}
	
	/**
	 * 根据ID批量逻辑删除(禁用)
	 * @param map
	 * @return 删除条数
	 */
	public int deleteByIds(Map<String, Object> map) {
		int num = userMapper.deleteByIds(map);
		// 后校验
		Assert.assertTrue(num > 0, ResultCode.MSG_ERROR);
		return num;
	}

	/**
	 * 根据ID逻辑删除(禁用)
	 * @param map
	 * @return 删除条数
	 */
	public int deleteById(Map<String, Object> map) {
		int num = 0;
		Integer id = (Integer) map.get("id");
		Assert.assertTrue(id > 0, ResultCode.MSG_ERROR);

		num = userMapper.deleteById(map);
		// 后校验
		Assert.assertTrue(num > 0, ResultCode.MSG_ERROR);
		return num;
	}

	/**
	 * 根据uuid删除用户
	 * @param map
	 * @return
	 */
	public int deleteByUUID(Map<String, Object> map) {
		return userMapper.deleteByUUID(map);
	}

	public User findByPrimaryKey(Integer id) {
		User user = null;
		// 预校验
		Assert.assertTrue(id > 0, ResultCode.MSG_PARAMS_NULL);
		user = userMapper.selectByPrimaryKey(id);
		return user;
	}

	public List<User> selectAll() {
		return userMapper.selectAll();
	}

	public int insert(User user) {
		int num = 0;
		// 校验逻辑,主用户usercode不能重复
		Assert.assertNotNull(user, ResultCode.MSG_PARAMS_NULL);
		if (CommonConstant.USER_TYPE_MAIN == user.getType())
		{
			UserSearchVO userVo = findByUserCode(user.getUserCode());
			Assert.assertNull(userVo, "该userCode用户已存在");
		}
		// 同一个登录账号(手机号,绑定uuid)不能存在多个角色
		User userTemp = userMapper.findByUuidAndRole(user.getUuid(), user.getUserRole());
		// 用户名不能重复
		Assert.assertNull(userTemp, "该手机已存在其他角色");
		userTemp = userMapper.findByUserName(user.getUserName());
		Assert.assertNull(userTemp, "用户名已存在");
		// 插入数据
		user.setCtime(DateUtils.getNowTime());
		num = userMapper.insert(user);
		return num;
	}

	public int update(User record) {
		int num = 0;
		// 预校验
		Assert.assertNotNull(record, ResultCode.MSG_PARAMS_NULL);
		record.setUtime(DateUtils.getNowTime());
		User userTemp = userMapper.findByUserName(record.getUserName());
		// 除了自己外用户名不能重复
		if (null != userTemp && !userTemp.getId().equals(record.getId())) {
			throw new RespExcption(ResultCode.FAILED, "用户名已存在");
		}
		
		// 如果操作为修改手机号
		if (StringUtils.isNotBlank(record.getPhone()))
		{
			User user = findByPrimaryKey(record.getId());
			if (user.getType() == CommonConstant.USER_TYPE_MAIN && !user.getPhone().equals(record.getPhone()))
			{
				userMapper.updateByPhone(user.getPhone(), record.getPhone());
			}
		}
		num = userMapper.updateByPrimaryKeySelective(record);
		// 后校验
		Assert.assertTrue(num != 0, ResultCode.MSG_ERROR);
		return num;
	}

	/**
	 * 更换手机绑定
	 */
	public int updatePhone(String oldPhone, String newPhone){
		return userMapper.updateByPhone(oldPhone, newPhone);
	}
	
	public PageInfo<User> findAllByPage(Map<String, Object> t, Integer pageNo, Integer pageSize) {
		pageNo = pageNo == null ? 1 : pageNo;
		pageSize = pageSize == null ? 10 : pageSize;
		PageHelper.startPage(pageNo, pageSize); // startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
		return PagedResult.toPageInfo(userMapper.getUserList());
	}

	/**
	 * 根据查询参数查询用户列表
	 * @param object
	 * @param pageDTO
	 * @return
	 */
	public List<UserSearchVO> selectUserBy(UserSearchDTO object, PageDTO pageDTO) {
		PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
		return userMapper.selectUserBy(object);
	}

	public List<User> findAllByPage(Integer pageNo, Integer pageSize) {
		pageNo = pageNo == null ? 1 : pageNo;
		pageSize = pageSize == null ? 10 : pageSize;
		PageHelper.startPage(pageNo, pageSize); // startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
		return userMapper.getUserList();
	}

	/**
	 * 查询所有类型的租户,不是登录账号
	 * @param object
	 * @param pageDto
	 * @return
	 */
	public List<UserVO> selectUser(FindUserDTO object, PageDTO pageDTO) {
		PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
		return userMapper.selectUser(object);
	}
}
